<?php 
require_once (dirname(__FILE__)."/../config/config.php");

addA2BToUser(2);
/**
 * 给中间平台的活动帐号绑定a2b帐号密码.
 * 1.先判断是否有可用的a2b帐号密码.  countA2BUnUsedUsers($package_type)
 * 2.然后查询出所有可以用的中间平台账户.
 * 3.按照可用a2b的数量去循环绑定(分配服务,绑定a2b)
 */
function addA2BToUser($package_type){
	$a2b_count=countA2BUnUsedUsers($package_type);
	if($a2b_count==0)
		return "001";//错误代码001 无可用a2b用户.
	$users=queryA2BUser();
	$user_count=count($users);
	$a2b_count>$user_count?$j=$user_count:$j=$a2b_count;
	for($i=0;$i<$j;$i++){
//	for($i=0;$i<1;$i++){
		//找一条可用的a2b帐号.
		$a2b_sql="SELECT * FROM zy_package_details WHERE package_type=2 and isused=0 ORDER BY package_details_id ASC LIMIT 0,1 ";
		$a2b_result = mysql_query($a2b_sql);
		$a2b = mysql_fetch_array($a2b_result);
		if($a2b=="")
			return "002";//错误代码002,找不到a2b用户.
		//分配服务.
		$userservice_sql="INSERT INTO `zy_user_service`(`user_id`,`service_id`,`valid_date`,`status`) VALUES (".$users[$i]['user_id'].",'3',CURDATE(),'1')";
		mysql_query($userservice_sql);
		$userservice_sql="SELECT @@IDENTITY";
		$userservice_result = mysql_query($userservice_sql);
		$userservice = mysql_fetch_array($userservice_result);
		$userservice_id=$userservice['0'];
		//绑定a2b
		$loginlist_sql="INSERT INTO `zy_login_list`(`user_service_id`,`field1`,`field2`,`field3`) VALUES ('$userservice_id','".$a2b['name']."','".$a2b['password']."','billing3.novatel.com.au');";
		mysql_query($loginlist_sql);
		//修改a2b帐号为已用状态
		$a2b_update_sql="update zy_package_details set isused=1 where package_details_id=".$a2b['package_details_id'];
		mysql_query($a2b_update_sql);
		//修改user 表示帐号已绑定成功,但帐号处于停用状态.
		$user_update_sql="update zy_user set isdelete=1 where user_id=".$users[$i]['user_id'];
		mysql_query($user_update_sql);
		echo ($i+1)."   从a2b_id=".$a2b['package_details_id']."   ,user_id=".$users[$i]['user_id']." 绑定了帐号.<br />";
	}
}
/**
 * 
 * 查询获取所有未激活的,且是活动用户.暂时以邮箱free@netcube.com.au为活动用户.isdelete=2时表示未绑定帐号.
 * 
 */
function queryA2BUser(){
	$sql="select * from zy_user where email='free@netcube.com.au' and isdelete=2";
	$result = mysql_query($sql);
	$i=0;
	$users=array();
  	while($rs=mysql_fetch_array($result)){
		$users[$i]=$rs;	
		$i++;
	}
	return $users;
}
/**
 * 查询获取还有多少A2B帐号可用.
 */
function countA2BUnUsedUsers($package_type){
	$sql="SELECT COUNT(package_details_id) FROM zy_package_details WHERE package_type=$package_type AND isused=0";
	$result=mysql_query($sql);
	$result=mysql_fetch_array($result);
	return $result[0];
}
?>